﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace Parylene_CVD.Tools
{
    public class PasswordEncryption
    {
        private static readonly string EncryptionKey = "YourStrongEncryptionKey123!"; // 加密密钥，确保安全存储

        // 加密密码
        public static string Encrypt(string plainText)
        {
            byte[] keyBytes = Encoding.UTF8.GetBytes(EncryptionKey.PadRight(32).Substring(0, 32)); // AES-256需要32字节密钥
            using (Aes aes = Aes.Create())
            {
                aes.Key = keyBytes;
                aes.GenerateIV(); // 生成随机IV
                byte[] iv = aes.IV;

                using (ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, iv))
                {
                    byte[] plainBytes = Encoding.UTF8.GetBytes(plainText);
                    byte[] cipherBytes = encryptor.TransformFinalBlock(plainBytes, 0, plainBytes.Length);

                    // 将IV附加到加密数据的前面存储，以便解密时使用
                    return Convert.ToBase64String(iv.Concat(cipherBytes).ToArray());
                }
            }
        }

        // 解密密码
        public static string Decrypt(string cipherText)
        {
            byte[] cipherBytesWithIV = Convert.FromBase64String(cipherText);
            byte[] keyBytes = Encoding.UTF8.GetBytes(EncryptionKey.PadRight(32).Substring(0, 32)); // AES-256需要32字节密钥

            // 提取IV和加密数据
            byte[] iv = cipherBytesWithIV.Take(16).ToArray(); // 前16字节是IV
            byte[] cipherBytes = cipherBytesWithIV.Skip(16).ToArray(); // 剩下的是加密数据

            using (Aes aes = Aes.Create())
            {
                aes.Key = keyBytes;
                aes.IV = iv;

                using (ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV))
                {
                    byte[] plainBytes = decryptor.TransformFinalBlock(cipherBytes, 0, cipherBytes.Length);
                    return Encoding.UTF8.GetString(plainBytes);
                }
            }
        }
    }
}
